<!doctype html>
<html>
<head>
<script>

var end;

function setupDB(){
	return this.createDatabase().then(createTable).then(insertEntry).then(readEntry).then(printResult);
}

function createDatabase(){
	return new Promise(function(resovle, reject) {
		console.log("prepare to create database..." + Date.now());
		this._db = openDatabase('mydb','1.0', 'JerryTestdb',1024);
		setTimeout( _createDatabaseOK.bind(this, resovle), 1000);
	});
}

function createTable(){
	return new Promise(function(resovle, reject) {
		console.log("prepare to create table..." + Date.now());
		this._db.transaction(function(query){
			query.executeSql('create table if not exists user(id unique, user, passwd)');
		});
		setTimeout( _createTableOK.bind(this, resovle), 1000);
	});
}

function _createTableOK(resovle){
	console.log("table created successfully..." + Date.now());
	resovle();
}

function _createDatabaseOK(resovle){
	console.log("database created successfully..." + Date.now());
	resovle(this._db);
}

function insertEntry(){
	return new Promise(function(resolve, reject) {
		this._db.transaction(function(query){
			query.executeSql("insert into user values (1,'Jerry','1234')");
		});
		setTimeout( _insertEntryOK.bind(this, resolve), 1000);
	});
}

function _insertEntryOK(resolve){
	console.log("entry inserted to table successfully..." + Date.now()); 
	resolve();
}

function readEntry() {
	return new Promise(function(resolve, reject) {
			this._db.transaction( function(query) {
				query.executeSql('select * from user',[],function(u,results) {
				setTimeout( _readEntryOK.bind(this, resolve, results), 1000);
			}); // end of query.executeSql
	 } // end of function(query)
	 ); // end of this._db.transaction
 });
}

function _readEntryOK(resolve, oResult){
	console.log("entry readed from DB successfully..." + Date.now());
	resolve(oResult);
}

function printResult(oResults){
	for( var i = 0; i < oResults.rows.length; i++) {
			document.writeln('id: ' + oResults.rows[i].id);
			document.writeln('user: ' + oResults.rows[i].user);
			document.writeln('passwd: ' + oResults.rows[i].passwd);
	}
	end = true;
}

function work(){
	if( end ){
		clearInterval(handle);
	}
	else{
		console.log(" working..." + Date.now());
	}
}

setupDB();
var handle = setInterval( work, 200);
</script>
</head>
</html>